<?php
namespace app\yangpay;

// use app\yangpay\AopClient;
use app\yangpay\SignData;
use alipay\aop\AopClient;
// require '/extend/alipay/alipay/aop/AopClient.php';
// use alipay\alipay\aop\request\
use alipay\aop\request\AlipayFundTransToaccountTransferRequest;
// require_once 'AopEncrypt.php';

class AlipayTransfer
{

    //支付宝网关地址
    // public $gateway_url = "https://openapi.alipaydev.com/gateway.do";
    public $gateway_url = "https://openapi.alipay.com/gateway.do";

    public $notify_url = '';//异步通知地址

    public $return_url = '';
    //支付宝公钥
    public $alipay_public_key;

    //商户私钥
    public $private_key;

    //应用id
    public $appid;

    //编码格式
    public $charset = "UTF-8";

    public $token = NULL;
    
    //返回数据格式
    public $format = "json";

    //签名方式
    public $signtype = "RSA";

    public function __construct($notify='', $return_url='')
    {

        $this->appid = "2019010962825780";
        $this->private_key = "MIIEpQIBAAKCAQEAxvmwbcYM1vPm2R5wEOa0/kd2SqCqv0cFhKvx6IfJZCxnJ11SxnIKN31jbEiDkPQ62Z7sf8AaeQRssaqVNJf1BNd2fXsv2TgsjFcuq9kFm/2qn//VOk6ZRGOkXAvW7Hxz6nFPEZedDCOtRqeCvIXbk2vXxGu9MbyNBtjqR/049i//3Rgog8WV11gie1yl7bDEO5nUePs7Z54ulwY0KSIDTJ2bBQUEgsOYaf/Y+wRK5+3yMsSohJRGYcdBN7OUrp4n9fZQ+/exdWbMzaJDPRA07FRqpxHkw3Cj2f5BSaKg42cpuoH5g6Bo76mpRx63sFIb+xjNgYLTerz3I+e5C7imnQIDAQABAoIBAQDFElzJ/NSOube05867DqXJC+J/e65iEOfIRb0tQAAZtVjdxjLL1fuEhi5I+3FDyoHXNO6sgQo3Pkihl4B8PN0y1GzJT49Op7KHtXnGPwatP4sVOYBpZZur/ry1ZgyS4Zi1ZVCY7f9gHJ3sUtDMBBA8bR2hr8wNTOCpHYK9lnIqchOxGwH9kyiB1vyUtiJ9WM7K9LSNfnA0kPayzMYKwI/bYKJ1vwQUfmjGSM5gaHxc52S1/1ki/Ds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6IfJZCxnJ11SxnIKN31jbEiDkPQ62Z7sf8AaeQRssaqVNJf1BNd2fXsv2TgsjFcuq9kFm/2qn//VOk6ZRGOkXAvW7Hxz6nFPEZedDCOtRqeCvIXbk2vXxGu9MbyNBtjqR/049i//3Rgog8WV11gie1yl7bDEO5nUePs7Z54ulwY0KSIDTJ2bBQUEgsOYaf/Y+wRK5+3yMsSohJRGYcdBN7OUrp4n9fZQ+/exdWbMzaJDPRA07FRqpxHkw3Cj2f5BSaKg42cpuoH5g6Bo76mpRx63sFIb+xjNgYLTerz3I+e5C7imnQIDAQAB";
        $this->charset = "UTF-8";
        $this->signtype= "RSA2";

        $notify = $notify ? $_SERVER['HTTP_HOST'].'/'.$notify : $_SERVER['HTTP_HOST'].'/alipay/notifyUrl';

        $return_url = $return_url ? 'http://www.dingtaism.com/'.$return_url : 'http://www.dingtaism.com/cherryWeb/index';


        $this->notify_url = $notify;
        $this->return_url = $return_url;

    }
   

    public function pay($data) 
    {

        //商户订单号，商户网站订单系统中唯一订单号，必填
        if ( isset($data['out_trade_no']) == false || empty($data['out_trade_no']) ) {
            $this->error = '商户订单号,不能为空';
            return false;
        }
        //订单名称，必填
        if ( isset($data['subject']) == false || empty($data['subject']) ) {
            $this->error = '订单名称，不能为空';
            return false;
        } 
        //付款金额，必填
        if ( isset($data['total_amount']) == false || empty($data['total_amount']) ) {
            $this->error = '付款金额，不能为空';
            return false;
        } 
        $params['out_trade_no']     = $data['out_trade_no'];
        $params['subject']          = $data['subject'];
        $params['total_amount']     = $data['total_amount'];
        $params['passback_params']  = $data['passback_params'];
        $params['body']         = isset($data['body']) ? $data['body'] : '';
        //超时时间
        $params['timeout_express'] = "2m";
        $params['productCode'] = "QUICK_WAP_PAY";
        $biz_content = json_encode($params,JSON_UNESCAPED_UNICODE);
        // dump($biz_content);die;

        $aop = new AopClient ();

        $aop->gatewayUrl    = $this->gateway_url;
        $aop->appId         = $this->appid;
        $aop->rsaPrivateKey =  $this->private_key;
        $aop->alipayrsaPublicKey = $this->alipay_public_key;
        $aop->apiVersion    ="1.0";
        $aop->postCharset   = $this->charset;
        $aop->format        = $this->format;
        $aop->signType      = $this->signtype;

        /*$apiParams['notify_url']  = $this->notify_url;
        $apiParams['return_url']  = $this->return_url;*/
        // $apiParams['return_url']  = $this->return_url;
        $apiParams['biz_content'] = $biz_content;
        // dump($aop->appId);die;
        // 开启页面信息输出
        //$aop->debugInfo=true;
        $result = $aop->pageExecute($apiParams,"post");
        if ($result) return $result;
        // echo $result;
        die;

    }

    // 转账
    public function transfer($data)
    {
    	//商户订单号，商户网站订单系统中唯一订单号，必填
        if ( isset($data['out_biz_no']) == false || empty($data['out_biz_no']) ) {
            $this->error = '转账订单号,不能为空';
            return 1;
            return json_error('转账订单号,不能为空');
            return false;
        }
        //收款方账户类型，支持邮箱和手机号格式，必填
        /*if ( isset($data['payee_type']) == false || empty($data['payee_type']) ) {
            $this->error = '收款方信息,不能为空';
            return 2;
            return json_error('收款方信息,不能为空');
            return false;
        }*/
        //收款方账户，必填
        if ( isset($data['payee_account']) == false || empty($data['payee_account']) ) {
            $this->error = '收款方信息，不能为空';
            return 3;
            return json_error('收款方信息,不能为空');
            return false;
        } 
        //付款金额，必填
        if ( isset($data['amount']) == false || empty($data['amount']) ) {
            $this->error = '转账金额，不能为空';
            return 4;
            return json_error('转账金额，不能为空');
            return false;
        } 
        /*"{" +
		"    \"out_biz_no\":\"3142321423432\"," +
		"    \"payee_type\":\"ALIPAY_LOGONID\"," +
		"    \"payee_account\":\"abc@sina.com\"," +
		"    \"amount\":\"12.23\"," +
		"    \"payer_show_name\":\"上海交通卡退款\"," +
		"    \"payee_real_name\":\"张三\"," +
		"    \"remark\":\"转账备注\"," +
		"  }"*/
        $params['out_biz_no']     	= $data['out_biz_no'];
        $params['payee_type']     	= 'ALIPAY_LOGONID';
        $params['payee_account']  	= $data['payee_account'];
        $params['amount']  		  	= $data['amount'];
        $params['payer_show_name']  = isset($data['payer_show_name']) ? $data['payer_show_name'] : '樱桃荟';
        $params['payee_real_name']  = isset($data['payee_real_name']) ? $data['payee_real_name'] : '';
        $params['remark']  			= isset($data['remark']) ? $data['remark'] : '';
        //超时时间
        /*$params['timeout_express'] 	= "2m";
        $params['productCode'] 		= "QUICK_WAP_PAY";*/
        $biz_content = json_encode($params,JSON_UNESCAPED_UNICODE);
        // dump($biz_content);die;

        $aop = new AopClient();

        $aop->gatewayUrl    		= $this->gateway_url;
        $aop->appId         		= $this->appid;
        $aop->rsaPrivateKey 		=  $this->private_key;
        $aop->alipayrsaPublicKey 	= $this->alipay_public_key;
        $aop->apiVersion    		= "1.0";
        $aop->postCharset   		= $this->charset;
        $aop->format        		= $this->format;
        $aop->signType      		= $this->signtype;

        /*$apiParams['notify_url']  = $this->notify_url;
        $apiParams['return_url']  = $this->return_url;*/
        $request = new AlipayFundTransToaccountTransferRequest();
        $request->setBizContent($biz_content);
        // var_dump($apiParams);die;
        // dump($aop->appId);die;
        // 开启页面信息输出
        //$aop->debugInfo=true;
        $result = $aop->execute($request);
        if ($result) return $result;
        // echo $result;
        die;
    }

    /**
     * 验签方法
     * @param $arr 验签支付宝返回的信息，使用支付宝公钥。
     * @return boolean
     */
    function check($arr)
    {
        $aop = new AopClient();
        $aop->alipayPublicKey = $this->alipay_public_key;
        $result = $aop->rsaCheckV1($arr, $this->alipay_public_key, $this->signtype);
        return $result;
    }

}

/**
 * 加密方法
 * @param string $str
 * @return string
 */
 function encrypt($str,$screct_key){
    //AES, 128 模式加密数据 CBC
    $screct_key = base64_decode($screct_key);
    $str = trim($str);
    $str = addPKCS7Padding($str);
    $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128,MCRYPT_MODE_CBC),1);
    $encrypt_str =  mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $screct_key, $str, MCRYPT_MODE_CBC);
    return base64_encode($encrypt_str);
}

/**
 * 解密方法
 * @param string $str
 * @return string
 */
 function decrypt($str,$screct_key){
    //AES, 128 模式加密数据 CBC
    $str = base64_decode($str);
    $screct_key = base64_decode($screct_key);
    $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128,MCRYPT_MODE_CBC),1);
    $encrypt_str =  mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $screct_key, $str, MCRYPT_MODE_CBC);
    $encrypt_str = trim($encrypt_str);

    $encrypt_str = stripPKSC7Padding($encrypt_str);
    return $encrypt_str;

}

/**
 * 填充算法
 * @param string $source
 * @return string
 */
function addPKCS7Padding($source){
    $source = trim($source);
    $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);

    $pad = $block - (strlen($source) % $block);
    if ($pad <= $block) {
        $char = chr($pad);
        $source .= str_repeat($char, $pad);
    }
    return $source;
}
/**
 * 移去填充算法
 * @param string $source
 * @return string
 */
function stripPKSC7Padding($source){
    $source = trim($source);
    $char = substr($source, -1);
    $num = ord($char);
    if($num==62)return $source;
    $source = substr($source,0,-$num);
    return $source;
}
